/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import com.ruipengkj.commons.util.MatcherFormatUtil;
import com.ruipengkj.commons.util.SafeProperties;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.JPanelFlowLayoutComponent;
import com.ruipengkj.component.RPJButtonWhite;
import com.ruipengkj.component.jdialog.BorderJPanel;
import com.ruipengkj.component.jdialog.IDialog;
import com.ruipengkj.component.jpanel.RepeatImagePanel;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.init.InitContext;
import com.ruipengkj.jdbc.ConnectionNetWork;
/**
 ** 说明：修改配置文件
 * 
 * @Author：黄盛强
 * @Date：2012-08-2
 **/
public class SetSqlDialog  extends IDialog  {
	private static final long serialVersionUID = 1L;

	private JTextField databasename;//数据库名称
	private JTextField ip;//ip地址
	private JTextField username;//sql账号
	private JPasswordField pass;//sql密码
	
	private JButton sureButton;//确定
	private JButton cancleButton;//取消
	
	public int isSuccess = 0;//成功 1、创建数据库成功2、连接数据库成功
	
	private SafeProperties pro=null;
	public SetSqlDialog(JDialog jd, String title, boolean b) {
		super(jd, title, b);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		this.setSize(350, 230);
		this.init();
		this.setVisible(true);
	}
	
	private void init() {
		databasename = new JTextField(30);
		ip = new JTextField(30);;//ip地址
		username = new JTextField(30);;//sql账号
		pass = new JPasswordField(30);;//sql密码
		
		Util.setSize(databasename, 30, 25);
		Util.setSize(ip, 30, 25);
		Util.setSize(username, 30, 25);
		Util.setSize(pass, 30, 25);
		
		databasename.addKeyListener(this);
		ip.addKeyListener(this);
		username.addKeyListener(this);
		pass.addKeyListener(this);
		
		sureButton = new RPJButtonWhite("确定");
		cancleButton = new RPJButtonWhite("取消");
		
		sureButton.addActionListener(this);
		cancleButton.addActionListener(this);
		
		JPanel main_jp = new BorderJPanel();
		BoxLayout boxLayout=new BoxLayout(main_jp,BoxLayout.Y_AXIS);
		main_jp.setLayout(boxLayout);
		main_jp.setOpaque(true);
		main_jp.setBackground(Util.PANEL_COLOR);
		
		main_jp.add(new JPanelFlowLayoutComponent(new Component[]{
				new JLabel(" IP 地  址："), ip
		}, FlowLayout.CENTER));
		main_jp.add(new JPanelFlowLayoutComponent(new Component[]{
				new JLabel("数据库名称："), databasename
		}, FlowLayout.CENTER));
		main_jp.add(new JPanelFlowLayoutComponent(new Component[]{
				new JLabel("数据库账号："), username
		}, FlowLayout.CENTER));
		main_jp.add(new JPanelFlowLayoutComponent(new Component[]{
				new JLabel("数据库密码："), pass
		}, FlowLayout.CENTER));
		
		JPanel jp = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_DOWN_BG_1).getImage());
		jp.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 10));
		jp.add(sureButton);
		jp.add(cancleButton);
		main_jp.add(jp);
		
		pro=(SafeProperties) InitContext.getinstance().LoadDataBaseData();
		databasename.setText(pro.getProperty(InitContext.database));
		ip.setText(pro.getProperty(InitContext.ip));
		username.setText(pro.getProperty(InitContext.username));
		pass.setText(pro.getProperty(InitContext.password));
		
		main_jp.setCursor(Util.CURSOR_DEFAULT);
		
		this.add(main_jp);
	}
	
	protected Dimension getTitleSize() {
		return new Dimension(110, 29);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == sureButton) {//保存文件，创建数据库
			if (check()){//保存文件
				this.save();
				//数据库创建, 连接数据库
				ConnectionNetWork connectionNetWork = new ConnectionNetWork(pro.getProperty(InitContext.username),
						pro.getProperty(InitContext.password), 
						pro.getProperty(InitContext.url).replace("/"+databasename.getText(), "/"));
				try {
					//创建数据库
					connectionNetWork.insert("create database "+databasename.getText() + " charset utf8");
					isSuccess = 1;
					connectionNetWork.close();
					this.dispose();
					return;
				} catch (Exception e1) {
//					e1.printStackTrace();
				} finally {
					connectionNetWork.close();
				}
				
				//数据库已经存在  或  连接数据库失败
				connectionNetWork = new ConnectionNetWork(pro.getProperty(InitContext.username),pro.getProperty(InitContext.password), pro.getProperty(InitContext.url));
				try {
					//连接数据库失败时
					if (connectionNetWork.getConnection() == null) {
						Util.showMessageDialog("连接数据库失败，请确认信息正确！");
						connectionNetWork.close();
						return;
					}
					
					isSuccess = 2;
					connectionNetWork.close();
				} catch (Exception e1) {
					e1.printStackTrace();
				} finally {
					connectionNetWork.close();
				}
				this.dispose();
			} 
		} else if (e.getSource() == cancleButton){
			this.dispose();
		}else {
			super.actionPerformed(e);
		}
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode() == KeyEvent.VK_ENTER) {
			sureButton.doClick();
		} else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
			this.dispose();
		}
	}
	
	//检查输入的数据是否正确
	private boolean check() {
		if (ip.getText().equals("")) {//ip不能为空
			Util.showMessageDialog("ip不能为空！");
			ip.requestFocus();
			return false;
		}
		if (!MatcherFormatUtil.checkIP4Scheme(ip.getText())) {//ip不能为空
			Util.showMessageDialog("ip填写不正确！");
			ip.requestFocus();
			return false;
		}
		if (databasename.getText().equals("")) {//数据库名称
			Util.showMessageDialog("数据库名称不能为空！");
			databasename.requestFocus();
			return false;
		}
		if (username.getText().equals("")) {//数据库名称
			Util.showMessageDialog("数据库登陆名不能为空！");
			username.requestFocus();
			return false;
		}
		if (pass.getPassword().length <= 0) {//数据库名称
			Util.showMessageDialog("数据库登录密码不能为空！");
			pass.requestFocus();
			return false;
		}
		return true;
	}
	
	private void save() {
		pro.setProperty(InitContext.database,databasename.getText().trim());
		pro.setProperty(InitContext.ip,ip.getText().trim());
		pro.setProperty(InitContext.username,username.getText().trim());
		pro.setProperty(InitContext.password,String.copyValueOf(pass.getPassword()));
		pro.setProperty(InitContext.url,"jdbc:mysql://"+ip.getText().trim()+":3306/"+databasename.getText().trim()+"?zeroDateTimeBehavior=round&useUnicode=true&characterEncoding=utf-8");
		InitContext.getinstance().saveDataBaseData(pro);
	}
	
	public static void main(String[] args) {
		SetSqlDialog dialog = new SetSqlDialog(null, "aa", true);
		Util.setSize(dialog, 400, 400);
		dialog.setVisible(true);
	}
}